#include <stdio.h>
#include <sys/stat.h> // 添加此行以包含stat函数的声明
#include <curl/curl.h>

#define FTP_SERVER "ftp://localhost"
#define FTP_USER "ftpuser"
#define FTP_PASS "19880605"
#define FILE_PATH "large_file.txt"

size_t read_callback(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    return fread(ptr, size, nmemb, stream);
}

void ftp_upload_with_resume(const char *local_file_path) {
    CURL *curl;
    CURLcode res;
    FILE *hd_src;
    struct stat file_info;

    // 获取文件信息
    if (stat(local_file_path, &file_info)) {
        printf("无法获取文件信息\n");
        return;
    }

    // 打开本地文件
    hd_src = fopen(local_file_path, "rb");
    if (!hd_src) {
        printf("无法打开本地文件\n");
        return;
    }

    // 初始化libcurl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if (curl) {
        // 设置FTP服务器信息
        curl_easy_setopt(curl, CURLOPT_URL, FTP_SERVER "/" FILE_PATH);
        curl_easy_setopt(curl, CURLOPT_USERPWD, FTP_USER ":" FTP_PASS);
        
        // 启用被动模式
        //curl_easy_setopt(curl, CURLOPT_FTP_USE_EPSV, 0L); // 禁用EPSV
        //curl_easy_setopt(curl, CURLOPT_FTP_USE_PASV, 1L); // 启用被动模式
        // 设置上传文件
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
        curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);
        
        // 设置文件大小
        curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)file_info.st_size);
        
        // 设置断点续传
        curl_easy_setopt(curl, CURLOPT_RESUME_FROM_LARGE, (curl_off_t)file_info.st_size);

        // 执行上传
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }

        // 清理
        curl_easy_cleanup(curl);
    }

    fclose(hd_src);
    curl_global_cleanup();
}




int main() {
    ftp_upload_with_resume("large_file.txt");
    return 0;
} 

/*
gcc -o curl_file_transfer curl_file_transfer.c -lcurl
*/